package com.cy.xdclassredis.controller;

import com.cy.xdclassredis.util.CommonUtil;
import com.cy.xdclassredis.util.JsonData;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/captcha")
public class KaptchaController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    @Qualifier("captchaProducer")
    private Producer captchaProducer;
    @GetMapping("/get_chaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response)  {
        String text = captchaProducer.createText();
        String captchaKey = getCaptchaKey(request);
        //十分钟过期
        stringRedisTemplate.opsForValue().set(captchaKey, text,10,TimeUnit.MINUTES);
        BufferedImage image = captchaProducer.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    @GetMapping("/send_code")
    public JsonData sendCode(String to,String captcha,HttpServletRequest request){
        String key = getCaptchaKey(request);
        String s = stringRedisTemplate.opsForValue().get(key);
        if (captcha !=null && s !=null && captcha.equalsIgnoreCase(s)){
            //to do 发送验证码的逻辑
            return JsonData.buildSuccess();
        }else {
            return JsonData.buildError("错误");
        }

    }
    private String getCaptchaKey(HttpServletRequest request){
        String ipAddr = CommonUtil.getIpAddr(request);
        String header = request.getHeader("User-Agent");
        String key = "user-service:captcha:"+CommonUtil.MD5(ipAddr+header);
        return key;
    }


}
